﻿using Microsoft.SharePoint;
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Office.Server.UserProfiles;
using System.Diagnostics;
using System.Web;
using System.Collections.Generic;
using System.Linq;
namespace Portal
{
    [ToolboxItemAttribute(false)]


    public partial class AttendanceAdmin : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]

        private string TotalPeopleCount
        {
            get;
            set;
        }
        private string PresentPeopleCount
        {
            get;
            set;
        }
        private string AbbsentPeopleCount
        {
            get;
            set;
        }
        public AttendanceAdmin()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                TotalProfiles();
                Present();
                Absent();
                
            }
            catch (Exception ex)
            {
                Common.LogPortal(ex);
            }
        }

        private void Absent()
        {
            lblAbsent.Text =Convert.ToString( Convert.ToInt32(TotalPeopleCount) - Convert.ToInt32(PresentPeopleCount));
        }

        private void Present()
        {

            SPListItemCollection items = TotalPeople();
            PresentPeopleCount = items.Count.ToString();
            lblPresent.Text = PresentPeopleCount;

        }

        private static SPListItemCollection TotalPeople()
        {
            var year = DateTime.Today.Year.ToString();
            var month = DateTime.Today.ToString("MMM");
            var day = DateTime.Today.Day.ToString();
            SPWeb web = SPContext.Current.Web;
            SPList attenlist = web.GetList("/Lists/Attendance/");
            Common.CreateFoldersIfNot(web, attenlist);
            SPQuery spQuery = new SPQuery();
            spQuery.ViewFields = @"  <FieldRef Name='ID'/><FieldRef Name='Employee'/>";
            SPFolder folder = attenlist.RootFolder.SubFolders[year].SubFolders[month].SubFolders[day];
            spQuery.Folder = folder;

            SPListItemCollection items = attenlist.GetItems(spQuery);
            return items;
        }

        private void TotalProfiles()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(
                    delegate()
                    {
                        using (SPSite thisSite = new SPSite(SPContext.Current.Site.Url))
                        {
                            HttpContext tmp = HttpContext.Current;
                            HttpContext.Current = null;
                            SPServiceContext serviceContext = SPServiceContext.GetContext(thisSite);
                            UserProfileManager mgr = new UserProfileManager(serviceContext, true);
                            TotalPeopleCount = mgr.Count.ToString();
                            lblTotal.Text = TotalPeopleCount;
                            HttpContext.Current = tmp;
                        }
                    }
                );
            }
            catch (Exception ex)
            {
                Common.LogPortal(ex);
            }

        }

        private void DetailsAttendence(string dtl)
        {
            
            List<string> everyone = new List<string>();
            List<string> present = new List<string>();
            GetAllPeopleFromUserProfile(everyone);
            GetAllPeoplePresentToday(present);

            var absentPeople = everyone.Except(present);
            grdAttendance.DataSource = everyone;
            grdAttendance.DataBind();
            
        }

        private static void GetAllPeopleFromUserProfile(List<string> everyone)
        {

            SPSecurity.RunWithElevatedPrivileges(
                     delegate()
                     {
                         using (SPSite thisSite = new SPSite(SPContext.Current.Site.Url))
                         {
                             HttpContext tmp = HttpContext.Current;
                             HttpContext.Current = null;
                             SPServiceContext serviceContext = SPServiceContext.GetContext(thisSite);
                             UserProfileManager mgr = new UserProfileManager(serviceContext, true);
                             IEnumerator userProfiles = mgr.GetEnumerator();
                             while (userProfiles.MoveNext())
                             {
                                 UserProfile userProfile = (UserProfile)userProfiles.Current;
                                 everyone.Add(userProfile.AccountName);
                             }
                             HttpContext.Current = tmp;
                         }
                     }
                 );
        }

        private static void GetAllPeoplePresentToday(List<string> present)
        {
            SPListItemCollection items = TotalPeople();
            foreach (SPListItem spItem in items)
            {
                present.Add(spItem["Employee"].ToString().Split('|')[1]);
            }
        }

        private void TotalDetails()
        {

        }

        protected void btnTotal_Click(object sender, EventArgs e)
        {
            List<string> everyone = new List<string>();
           
            GetAllPeopleFromUserProfile(everyone);
           

          
            grdAttendance.DataSource = everyone;
            grdAttendance.DataBind();
        }

        protected void btnPresent_Click(object sender, EventArgs e)
        {
            
            List<string> present = new List<string>();
           
            GetAllPeoplePresentToday(present);

          
            grdAttendance.DataSource = present;
            grdAttendance.DataBind();
        }

        protected void btnAbsent_Click(object sender, EventArgs e)
        {
            List<string> everyone = new List<string>();
            List<string> present = new List<string>();
            GetAllPeopleFromUserProfile(everyone);
            GetAllPeoplePresentToday(present);

            var absentPeople = everyone.Except(present);
            grdAttendance.DataSource = absentPeople;
            grdAttendance.DataBind();
        }

      

       
    }
}
